package me.zhengjie.modules.forecast.rest;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.heshuo.amm.exception.DatabaseException;
import com.heshuo.amm.model.FlightConfig;
import com.heshuo.amm.service.IFlightConfigService;
import me.zhengjie.modules.forecast.dto.FlightConfigDTO;
import me.zhengjie.modules.forecast.dto.FlightFileDTO;

@RestController
@RequestMapping("api")
public class FlightFileController {
Logger log = LoggerFactory.getLogger(FlightFileController.class);
	@Autowired
	IFlightConfigService flightConfigService;
	
	@GetMapping(value="/flight/getConfigList")
	public ResponseEntity getConfigList(){
		List<FlightConfig> list = null;
		List<Map> result=new ArrayList();
		try {
			list = flightConfigService.listAllFlightConfigInfo();
			Map<String,Object> fcm ;
			for(FlightConfig fc:list){
				fcm = new HashMap<String, Object>();
				fcm.put("isDefault", fc.getIsDefault());
				fcm.put("contentMap",fc.getContentMap());
				fcm.put("createDate", fc.getCreateDate());
				fcm.put("landAirport", fc.getLandAirport());
				fcm.put("departAirport", fc.getDepartAirport());
				fcm.put("fileName", fc.getFileName());
				fcm.put("id", fc.getId());
				result.add(fcm);
			}
		} catch (DatabaseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new ResponseEntity(result,HttpStatus.OK);
	}
	@PostMapping(value="/flight/saveConfig")
	public ResponseEntity saveConfig(@RequestBody FlightConfig fc){
		try {
//			fc.setContentBlob(com.heshuo.amm.util.MiscUtils.ObjectToBlob(fc.getContentMap()));
			flightConfigService.saveFlightConfigInfo(fc);
		} catch (DatabaseException e) {
			return new ResponseEntity(false,HttpStatus.OK);
		}
		return new ResponseEntity(true,HttpStatus.OK);
	}
	@PostMapping(value="/flight/delConfig")
	public ResponseEntity delConfig(@RequestBody FlightConfig fc){
		boolean res=false;
		try {
			
			List<FlightConfig> list = flightConfigService.listAllFlightConfigInfo();
			for(FlightConfig fcl:list){
				if(fcl.getId().equals(fc.getId())){
					flightConfigService.deleteFlightConfigInfo(fcl);
					res=true;
					break;
				}
			}
		} catch (DatabaseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ResponseEntity(res,HttpStatus.OK);
		}		
		return new ResponseEntity(res,HttpStatus.OK);
	}
	@PostMapping(value="/flight/setDefault")
	public ResponseEntity setDefault(@RequestBody FlightConfig fc){
		boolean res=false;
		try {
			
			List<FlightConfig> list = flightConfigService.listAllFlightConfigInfo();
			for(FlightConfig fcl:list){
				if(fcl.getIsDefault().equals("1")){
					fcl.setIsDefault("0");
//					fcl.setContentBlob(com.heshuo.amm.util.MiscUtils.ObjectToBlob(fcl.getContentMap()));
					flightConfigService.saveFlightConfigInfo(fcl);
				}
				if(fcl.getId().equals(fc.getId())){
					fcl.setIsDefault("1");
//					fcl.setContentBlob(com.heshuo.amm.util.MiscUtils.ObjectToBlob(fcl.getContentMap()));
					flightConfigService.saveFlightConfigInfo(fcl);
					res=true;
				}
			}
		} catch (DatabaseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ResponseEntity(res,HttpStatus.OK);
		
		}catch(Exception e){
			e.printStackTrace();
		}
		return new ResponseEntity(res,HttpStatus.OK);
	}
	@PostMapping(value="/flight/makeFile",produces = "application/json; charset=utf-8")
	public ResponseEntity makeFile(@RequestBody FlightConfigDTO fc) throws UnsupportedEncodingException {
		FlightFileDTO ff = new FlightFileDTO(fc,fc.getCreateDate());
		String folder=System.getProperty("java.io.tmpdir");
		int result = ff.makePdfFile(folder);
		log.info("makePdfFile result:"+result);
		log.info("makeFile path as:"+ff.pdfFile);
		
		return new ResponseEntity(ff.pdfFile.replace(folder, ""),HttpStatus.OK);
	}
	@PostMapping(value="/flight/getFile")
	public void getFile(@RequestBody String fileName,HttpServletRequest request,
            HttpServletResponse response) throws UnsupportedEncodingException{
		String folder=System.getProperty("java.io.tmpdir");
		File file = new File(folder,fileName);
		if(file.exists()){
			response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下载文件能正常显示中文
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes("gb2312"),"iso-8859-1"));

            // 实现文件下载
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                System.out.println("Download the song successfully!");
            }
            catch (Exception e) {
                System.out.println("Download the song failed!");
            }
            finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
//                file.delete();
            }
		}
	}
	
}
